﻿using DryIoc;
using PLCSharp.CoreModel.Prism;
using PLCSharp.CoreModel.Tools;
using PLCSharp.Models;
using PLCSharp.Views.Connects.Socket;
using PLCSharp.Views.Vision.Camera;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Collections.ObjectModel;
using static PLCSharp.Views.Connects.Connect;
namespace PLCSharp.Views.Connects
{
    [Model]
    public class ConnectsModel : ModelBase
    {
        public GlobalModel GlobalModel { get; set; }
        public ConnectsModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
        {
 
        }
        public void Init(GlobalModel globalModel)
        {
            GlobalModel = globalModel;

            foreach (var item in _DatasContext.Connects)
            {
                switch (item.Type)
                {
                    case ProtocolType.SocketClient:
                        {
                            var connect = new SocketClient
                            {
                                ID = item.ID,
                                Name = item.Name,
                                IP = item.IP,
                                Port = item.Port,
                                Type = item.Type,
                                Comment = item.Comment,
                                Params = item.Params,
                             
                            };
                            connect.Params.Prompt = "";
                            Connects.Add(connect);
                        }
                        break;
                    case ProtocolType.SocketSever:
                        {
                            var connect = new SocketServer
                            {
                                ID = item.ID,
                                Name = item.Name,
                                IP = item.IP,
                                Port = item.Port,
                                Type = item.Type,
                                Comment = item.Comment,
                                Clients = item.Clients,
                              
                            };
                            connect.Params.Prompt = "";
                            connect.Clients.ToList().ForEach(c => c.Params.Prompt = "");
                            Connects.Add(connect);

                        }
                        break;
                    case ProtocolType.ModbusTcpClient:
                        break;
                    case ProtocolType.ModbusTcpServer:
                        break;
                    default:
                        break;
                }

            }


        }
        #region Connect

        private ObservableCollection<Connect> _Connects = [];

        public ObservableCollection<Connect> Connects
        {
            get { return _Connects; }
            set { SetProperty(ref _Connects, value); }
        }

        private Connect _SelectedConnect;

        public Connect SelectedConnect
        {
            get { return _SelectedConnect; }
            set { SetProperty(ref _SelectedConnect, value); }
        }

        private DelegateCommand<string> _ConnectsManage;

        public DelegateCommand<string> ConnectsManage =>
            _ConnectsManage ??= new DelegateCommand<string>(ExecuteConnectsManage);

        private void ExecuteConnectsManage(string cmd)
        {
            switch (cmd)
            {
                case "New":
                    _dialogService.ShowDialog("NewConnect", r =>
                    {
                        if (r.Result== ButtonResult.Yes)
                        {
                     
                                var type = r.Parameters.GetValue<ProtocolType>("Type");

                                switch (type)
                                {
                                    case ProtocolType.SocketClient:
                                        Connects.Add(new SocketClient()
                                        {
                                            Name = r.Parameters.GetValue<string>("Name"),
                                            IP = r.Parameters.GetValue<string>("IP"),
                                            Port = r.Parameters.GetValue<int>("Port"),
                                            Comment = r.Parameters.GetValue<string>("Comment"),
                                            Type = ProtocolType.SocketClient

                                        });
                                        break;
                                    case ProtocolType.SocketSever:
                                        Connects.Add(new SocketServer()
                                        {
                                            Name = r.Parameters.GetValue<string>("Name"),
                                            IP = r.Parameters.GetValue<string>("IP"),
                                            Port = r.Parameters.GetValue<int>("Port"),
                                            Comment = r.Parameters.GetValue<string>("Comment"),
                                            Type = ProtocolType.SocketSever
                                        });
                                        break;
                                    case ProtocolType.ModbusTcpClient:
                                        break;
                                    case ProtocolType.ModbusTcpServer:
                                        break;
                                    case ProtocolType.SerialPort:
                                        break;
                                    default:
                                        break;
                                }

                        
                        }
                    });
                    break;

                case "Save":
                    SaveConnects();
                    break;

                case "Config":
                    switch (SelectedConnect.Type)
                    {
                        case ProtocolType.SocketClient:
                            {
                                var client = Connects.Where(c => c.ID == SelectedConnect.ID).FirstOrDefault();

                                if (client == null)
                                {
                                    client = _container.Resolve<SocketClient>();
                                    {
                                        client.Name = SelectedConnect.Name;
                                        client.IP = SelectedConnect.IP;
                                        client.Port = SelectedConnect.Port;
                                    }
                                    ;
                                    Connects.Add(client);
                                }


                                _dialogService.Show("SocketClientConfig", new DialogParameters($"Name={SelectedConnect.Name}"), r =>
                                {


                                });
                            }
                            break;
                        case ProtocolType.SocketSever:
                            {
                                var server = Connects.Where(c => c.ID == SelectedConnect.ID).FirstOrDefault();

                                if (server == null)
                                {
                                    server = _container.Resolve<SocketServer>();
                                    {
                                        server.Name = SelectedConnect.Name;
                                        server.IP = SelectedConnect.IP;
                                        server.Port = SelectedConnect.Port;
                                    }
                                    ;
                                    Connects.Add(server);
                                }


                                _dialogService.Show("SocketServerConfig", new DialogParameters($"Name={SelectedConnect.Name}"), r =>
                                {


                                });
                            }
                            break;
                        case ProtocolType.ModbusTcpClient:
                            break;
                        case ProtocolType.ModbusTcpServer:
                            break;
                        default:
                            break;
                    }
                    break;

                case "Remove":
                    if (SelectedConnect != null)
                    {
                        if (_DatasContext.Connects.Any(h => h.ID == SelectedConnect.ID))
                        {
                            var removeConnect = _DatasContext.Connects.Where(h => h.ID == SelectedConnect.ID).FirstOrDefault();

                            _DatasContext.Connects.Remove(removeConnect);
                            var name = SelectedConnect.Name;
                            SelectedConnect.Close();
                            Connects.Remove(SelectedConnect);
                            SendErr($"已删除：{name}", ErrType.ShowDialog);
                            _DatasContext.Save();
                        }


                    }
                    break;
            }
        }
 
        public void SaveConnects()
        {
            var names = new List<string>();

            foreach (var item in Connects)
            {
                if (string.IsNullOrEmpty(item.Name))
                {
                    SendErr($"保存失败，名称{item.Name}不合适！", ErrType.ShowDialog);
                    return;
                }

                if (names.Contains(item.Name))
                {
                    SendErr($"保存失败，重复的名称{item.Name}！", ErrType.ShowDialog);
                    return;
                }
                else
                {
                    names.Add(item.Name);
                }
            }


            foreach (var item in Connects)
            {
                if (!_DatasContext.Connects.Any(h => h.ID == item.ID))
                {
                    _DatasContext.Connects.Add(item);
                }
                else
                {
                    var connect = _DatasContext.Connects.Where(c => c.ID == item.ID).FirstOrDefault();
                    connect.Name = item.Name;
                    connect.IP = item.IP;
                    connect.Comment = item.Comment;
                    connect.Port = item.Port;
                    connect.Params = item.Params;
                    connect.Clients = item.Clients;
                }

            }


            SelectedConnect.Params.Prompt = "";
            _DatasContext.Save();
        }

        #endregion ProtocolHost

 

    }
}